# -*- coding: utf-8 -*-
import weather
import WxPusher
import json
from datetime import datetime
import os
from apscheduler.schedulers.blocking import BlockingScheduler
import logging.handlers

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


def logInit():
    # 创建 handler 输出到文件
    handler = logging.FileHandler("out.log", mode='w', encoding='utf-8')
    handler.setLevel(logging.INFO)

    # handler 输出到控制台
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    # 创建 logging format
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    ch.setFormatter(formatter)

    # add the handlers to the logger
    logger.addHandler(handler)
    logger.addHandler(ch)

def getWeatherHtml():
    result = {'result' : False}
    weatherResult = weather.getWeather(101210106)
    if weatherResult['result'] == True:
        logger.info("获取天气数据成功")
        pushHtml = '''  <h1> 每日天气</h1>
                    <p>今天天气：%s</p>
                    <p>今天温度：%d ~ %d</p>
                    <p>昨天最高温差值：%d</p>
                    <p>昨天最底温差值：%d</p>
                    '''%(weatherResult['data']['todayType'], weatherResult['data']['todayLow'], weatherResult['data']['todayHigh'],\
                                 weatherResult['data']['subYesterdayLow'], weatherResult['data']['subYesterdayHigh'])
        result['result'] = True;
        result['data'] = pushHtml;
        return result
    else:
        logger.error("获取天气信息失败")
        logger.error(weatherResult['data'])

    return result

def pushToWechartHtml(pushHtml):
    result = WxPusher.pushToWechartHtml(pushHtml) 
    if result['result'] == True:
        logger.info("推送微信成功")
        return True
    else:
        logger.error("获取天气信息失败：")
        logger.error(result['data'])
    return False
    

def pushWeather():
    pushHtml = getWeatherHtml()
    if pushHtml['result'] == True:
        pushToWechartHtml(pushHtml['data'])


if __name__ == '__main__':
    logInit()
    scheduler = BlockingScheduler()
    scheduler.add_job(pushWeather, 'cron', hour=5,minute=00)
    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass

